﻿using UnityEngine;

namespace ZFramework.Runtime
{
    public class AssetLoaderMgr : FrameworkManagerBase, IAssetLoaderMgr
    {
        private LoadAssetCallbacks _loadAssetCallbacks;

        private IEventManager _eventMgr;

        private IResourceMgr _resourceMgr;

        protected override void Awake()
        {
            base.Awake();
            _loadAssetCallbacks = new LoadAssetCallbacks(LoadAssetSuccessCallback, LoadAssetFailureCallback);
        }

        void Start()
        {
            _eventMgr = FrameworkManagerManager.GetManager<EventManager>();
            if (_eventMgr == null)
            {
                Log.Error("EventMgr is invalid.");
                return;
            }
            _resourceMgr = FrameworkManagerManager.GetManager<YooResourceMgr>();
            if (_resourceMgr == null)
            {
                Log.Error("YooResourceMgr is invalid.");
                return;
            }
        }

        public override void OnUpdate(float elapseSeconds, float realElapseSeconds)
        {
        }

        public override void Shutdown()
        {
        }

        public void LoadAssetAsync<T>(string assetPath) where T : Object
        {
            _resourceMgr.LoadAssetAsync<T>(assetPath, _loadAssetCallbacks);
        }
        
        public void UnloadAsset(string assetPath)
        {
            _resourceMgr.UnloadAsset(assetPath);
        }

        private void LoadAssetSuccessCallback(string assetPath, Object asset, float duration, object userData)
        {
            _eventMgr.Fire(this, AssetLoadSuccessEventArgs.Create(asset, assetPath));
        }

        private void LoadAssetFailureCallback(string assetName, string errorMessage, object userData)
        {
        }
    }
}